package com.liuhung.base.view.excel;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import com.liuhung.base.excel.ExcelUtil;

public class ExcelView extends AbstractExcelView{

	@Override
	protected void buildExcelDocument(Map<String, Object> model,
			HSSFWorkbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
			//获取要生成的文件的名称
		 	String filename = (String) (model.get("fileName")==null?"无标题.xls":model.get("fileName")+".xls");
		 	filename = ExcelUtil.encodeFilename(filename, request);//处理中文文件名
		 	 
		 	String title = (String) (model.get("title")==null?"未设置标题":model.get("title"));
		 	
		 	String[] header = (String[]) model.get("header");
		 	short i = (short) header.length;
		 	
		 	List<?> list = (List<?>)model.get("list");
	        
			Sheet sheet = workbook.createSheet("sheet1");
			//创建第一行标题
			Row row = sheet.createRow(0);
			row.setHeightInPoints(36);
			Cell titleCell =row.createCell(0);
			
			titleCell.setCellValue(title);
			titleCell.setCellStyle(ExcelUtil.getStyleOne(workbook));
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, i-1));
			
			
			Row row1 = sheet.createRow(1);
			row1.setHeightInPoints(26);
			Cell remarkCell =row1.createCell(0);
			remarkCell.setCellValue("本数据来源于西北医疗平台.http://www.xibeiyiliao.cn");
			remarkCell.setCellStyle(ExcelUtil.getStyleOne(workbook));
			sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, i-1));
			
			int width[] =new int[]{20,20,16,16,24,20,36,20,16};//列宽..
			// 定义表头
			int j=0;
System.out.println("标题长度"+header.length);
			Row row2 = sheet.createRow(2);
			for (String t: header) {
				sheet.setColumnWidth(j, width[j] * 256 );
				Cell cell = row2.createCell(j++);
				cell.setCellValue(t);
				cell.setCellStyle(ExcelUtil.getStyleOne(workbook));
			}
			
	        //数据导入
			for (int k = 0;k < list.size(); k++) {
				Object p =  list.get(k);
				Class<? extends Object> classType = p.getClass();
				Field field[] = classType.getDeclaredFields();
				Row row3 = sheet.createRow(k + 3);
				int s=0;
				for(Field f: field)
				{
					Object v = invokeMethod(p,f.getName(),null);
					Cell cell = row3.createCell(s++);
					
					if(f.getType().equals(Date.class))
					{
						SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
						Date date =(Date)v;
						String dateString = format.format(date);
						cell.setCellValue(dateString);
						sheet.setColumnWidth(1, (dateString.getBytes().length) * 256 );
					}
					else{
						String value =(String)v;
						cell.setCellValue(value);
					}
					cell.setCellStyle(ExcelUtil.getStyleTwo(workbook));
					
				}
			}
	        response.setContentType("application/vnd.ms-excel");     
	        response.setHeader("Content-disposition", "attachment;filename=" + filename);     
	        OutputStream ouputStream = response.getOutputStream();     
	        workbook.write(ouputStream);     
	        ouputStream.flush();     
	        ouputStream.close();     
	}
	
	 /** 
     * 获得对象属性的值 
     */  
    private static Object invokeMethod(Object owner, String methodName,  
            Object[] args) throws Exception {  
        Class<? extends Object> ownerClass = owner.getClass();  
        methodName = methodName.substring(0, 1).toUpperCase()  
                + methodName.substring(1);  
        Method method = null;  
        try {  
            method = ownerClass.getMethod("get" + methodName);  
        } catch (SecurityException e) {  
        } catch (NoSuchMethodException e) {  
            return " can't find 'get" + methodName + "' method";  
        }  
        return method.invoke(owner);  
    }  

}
